#!/bin/sh

#  Copyright 2009 Giles Burgess
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

MKRBAT=$(cd ${0%/*} && echo $PWD/${0##*/})
while ([ -h "${MKRBAT}" ]) do MKRBAT=`readlink "${MKRBAT}"`; done
# echo BATCH ${MKRBAT}
MKRDIR=`dirname "$MKRBAT"`

DIR=build
CLASS=Make
ARGS=
CP=${DIR}

while (( "$#" )) ; do
  if [ "$1" == "--build" ] ; then
    shift
    CLASS=$1
  elif [ "$1" == "--cp" ] ; then
    shift
    CP="$CP:$1"
  else
    ARGS="$ARGS $1"
  fi
  shift
done

for jar in $(find ${DIR} -name *.jar)
do
  CP="$CP:$jar"
done
for jar in ${MKRDIR}/build/*.jar
do
  CP="$CP:$jar"
done
SRC=${DIR}/${CLASS//\./\/}.java
DEFS="-Dmake.java.dir=${DIR}"

if [ -e "$SRC" ] ; then
  # echo CLASSPATH ${CP}
  javac -cp ${CP} ${SRC}
  if [ $? != 0 ] ; then
    exit 1
  fi
  java -cp ${CP} ${DEFS} ${CLASS} ${ARGS}
  find ${DIR} -name \*.class -exec rm {} \;
else
  echo Missing source file: ${SRC}
  exit 1
fi

exit 0
